package Search;

import java.io.*;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.annotation.WebServlet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletContext;

import SearchList.SearchList;

@WebServlet("/Servlet")
public class Servlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        response.setContentType("text/html");
        String name = request.getParameter("word");
        String radio = request.getParameter("radio");
        String path = request.getContextPath();

        if(name != "") {
            //if the input is not null, read the file
            //System.out.println(name);
            response.setContentType("text/html; charset=utf-8");
            name = name.toLowerCase();      //change it to lower case
            try {

                List<SearchList> searchLists = new ArrayList<SearchList>();
                System.out.println(name);
                String character[] = name.split(" ");   //if the user input a sentence, split it into different words.
                if (radio.equals("Accurate")) {
                    for (int d = 0; d < character.length; d++) {
                        System.out.println(character[d]);
                        searchLists = accurateSearch(searchLists, character[d]);
                    }
                }
                else {
                    for (int d = 0; d < character.length; d++) {
                        System.out.println(character[d]);
                        searchLists = likeSearch(searchLists, character[d]);
                    }
                }

                for (int counter = 0; counter < searchLists.size(); counter++) {
                    Collections.sort(searchLists.get(counter).getLine());     //sort the line one by one
                }


                //search the content for user
                //search all the address and save them in searchLists object

                ArrayList<String> addresslists = new ArrayList<String>();
                String temp1[] = searchLists.get(0).getAddress().split(":", 3);
                String address1[] = temp1[2].split("/", 4);
                addresslists.add(address1[3]);      //get all the address from the searchLists
                for (int b = 1; b < searchLists.size(); b++) {      //build a for loop to read them all
                    String tempin[] = searchLists.get(b).getAddress().split(":", 3);
                    String addressin[] = tempin[2].split("/", 4);
                    if (addresslists.contains(addressin[3])) {     //judge whether the address already exist or not
                        continue;       //if the address already existed
                    } else {
                        addresslists.add(addressin[3]);     //if the address is not exist
                    }
                }
                System.out.println(addresslists);

                for (int c = 0; c < addresslists.size(); c++) {
                    searchLists = read(searchLists, addresslists.get(c));    //call the read function
                }

                request.setAttribute("search", searchLists);    //set the attribute



            } catch (Exception e) {
                e.printStackTrace();
            }

            RequestDispatcher dispatcher = request.getRequestDispatcher("Search.jsp");
            dispatcher.forward(request, response);

        }
        else {
            //System.out.println("what");
            //if the input is null, refresh the index page
            RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
            dispatcher.forward(request, response);
        }

    }

    //used to get the actual line that user want
    public List<SearchList> read(List<SearchList> searchLists, String addressfile){
        //search the content for user
        try {
            //File searchFile = new File("http://172.16.199.117:8080/demo1_war/WEB-INF/classes/Search/" + addressfile);

            File searchFile = new File(getServletContext().getRealPath(addressfile));

            FileReader searchFilereader = new FileReader(searchFile);
            BufferedReader bufferedReader = new BufferedReader(searchFilereader);
            String content = bufferedReader.readLine();//read the first line of the file
            bufferedReader.mark((int) searchFile.length());
            int number = 1;     //record the number of line in this article
            int numberSearch = 0;   //record the number of searchLists
            int n = 0;
            while (numberSearch != searchLists.size()) {    //compare how many searchLists are there
                String temp[] = searchLists.get(numberSearch).getAddress().split(":", 3);
                String address[] = temp[2].split("/", 4);
                if (address[3].equals(addressfile)) {
                    //System.out.println(address[3]);
                    n = 0;
                    ArrayList<String> contentSearch = new ArrayList<String>();
                    while (n < searchLists.get(numberSearch).getLine().size()) {   //compare how many lines in one searchLists
                        while (true) {
                            if (searchLists.get(numberSearch).getLine().get(n) == number) { //judge whether this line is the one that we want
                                contentSearch.add(content); //add the line into a arraylist
                                break;
                            } else {
                                number++;
                                content = bufferedReader.readLine();
                                if (content == null)
                                {
                                   break;
                                }
                            }
                        }
                        n++;
                    }
                    searchLists.get(numberSearch).setContent(contentSearch);
                    number = 1;
                    bufferedReader.reset();     //return to the first line of the file
                    numberSearch++;
                } else {
                    numberSearch++;
                }
            }
            System.out.println("Finished " + addressfile);
            bufferedReader.close();

            //search the content for user
            return searchLists;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return searchLists;
    }

    public List<SearchList> accurateSearch(List<SearchList> searchLists, String name){
        try {
            //String pathname = "http://172.16.199.117:8080/demo1_war/WEB-INF/classes/Search/result4.txt";
            //String pathname = "C:\\Users\\LEI\\IdeaProjects\\webDemo\\demo1\\src\\Search\\result4.txt";
            String pathname = getServletContext().getRealPath("result4.txt");
            File filename = new File(pathname); // read the filename above
            FileReader fileReader = new FileReader(filename);
            BufferedReader br = new BufferedReader(fileReader); //build a object which will transfer the content into a language that computer can read

            String line = br.readLine();
            int i = 0;

            while (line != null) {
                String word[] = line.split("\\+", 2);
                if (word[0].equals(name)) {
                    String address[] = word[1].split("\\+", 2);
                    String[] line1 = address[1].split("\\+");
                    ArrayList<Integer> line2 = new ArrayList<Integer>();
                    for (int k = 0; k < line1.length; k++) {
                        //line2.add(line1[k]);
                        int a = Integer.parseInt(line1[k]);
                        line2.add(a);
                    }
                    SearchList list = new SearchList(word[0], address[0], line2);
                    searchLists.add(list);
                    line = br.readLine();
                    continue;
                } else {
                    line = br.readLine(); // read only one line of file
                    continue;
                }
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return searchLists;
    }

    public List<SearchList> likeSearch(List<SearchList> searchLists, String name){

        try {
            //String pathname = "http://172.16.199.117:8080/demo1_war/WEB-INF/classes/Search/result4.txt";
            //String pathname = "C:\\Users\\LEI\\IdeaProjects\\webDemo\\demo1\\src\\Search\\result4.txt";
            String pathname = getServletContext().getRealPath("result4.txt");
            File filename = new File(pathname); // read the filename above
            FileReader fileReader = new FileReader(filename);
            BufferedReader br = new BufferedReader(fileReader); //build a object which will transfer the content into a language that computer can read
            String line = br.readLine();
            int i = 0;
            while (line != null) {
                String word[] = line.split("\\+", 2);
                if (word[0].contains(name)) {
                    String address[] = word[1].split("\\+", 2);
                    String[] line1 = address[1].split("\\+");
                    ArrayList<Integer> line2 = new ArrayList<Integer>();    //create a arraylist to save the address
                    for (int k = 0; k < line1.length; k++) {
                        //line2.add(line1[k]);
                        int a = Integer.parseInt(line1[k]);     //change the address from string type to int type
                        line2.add(a);
                    }
                    SearchList list = new SearchList(word[0], address[0], line2);   //constrcut a searchlist class
                    searchLists.add(list);
                    line = br.readLine();
                    continue;
                } else {
                    line = br.readLine(); // read only one line of file
                    continue;
                }
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return searchLists;
    }

}


